<?php
class PayAction extends Action{
	
	/** 支付成功后的处理 
	 * 支付前应该所有数据都放入session中应该更安全。待定？？
	 * */
	function paySuccess(){
		
		$this->gotoLogin();
		$itemType	=	$_POST['itemType'];	//$("#paytypeselect").find("#itemType").val()
		$itemId		=	$_POST['itemId'];	//itemId : $("#paytypeselect").find("#itemId").val()
		//$payType	=	$_POST['payType'];	//payType : $("#paytypeselect").find("#payType").val()
		$result['status']=0;
		$result['msg']='参数错误！';
		$paydict = service('Dict')->getAllDirectSubDicts('pay','code');
		if(!in_array($itemType,$paydict))exit(json_encode($result));
		if(empty($itemId))exit(json_encode($result));
		
		Log::write('PayAction.paySuccess()->itemId='.$itemId.'  itemType='.$itemType,Log::DEBUG,Log::FILE);
		
		if($itemType=='pay_order'){
			Log::write('PayAction.paySuccess()->itemId='.$itemId.'  itemType='.$itemType."  执行订单成功后的操作！",Log::DEBUG,Log::FILE);
		
			$result = $this->_payOrderSuccess($itemId);
		}
		if($itemType=='pay_charge'){
			Log::write('PayAction.paySuccess()->itemId='.$itemId.'  itemType='.$itemType."  执行充值成功后的操作！",Log::DEBUG,Log::FILE);
		
			$uaccount = service('UserAccount')->refresh4UserCash();
			$result['status']=1;
			$result['msg']='充值成功！账户余额：'.formatMoney($uaccount['current_money']);;
		}
		exit(json_encode($result));
	}
	
	
	private function _payOrderSuccess($order_id){
		$result['status']=0;
		$result['msg']='未选择订单！';
		if(empty($order_id))exit(json_encode($result));
		//$orderinfo = service('Order')->get4UserById($order_id);
		$result = service('Order')->do4UserPayOrder($order_id);
		if($result['status']==1||$result['paystatus']=='pay'){
			$result['status']=1;
			$cashpayamount = service('Pay')->countOrderUseMoneyPaiedAmount($result['data']['orderinfo']['id'],'pay_order');
			//更新返利
			model('Agent')->addRebate(	 $result['data']['orderinfo']['user_id']
										,$result['data']['orderinfo']['id']
										,$result['data']['orderinfo']['total_fee']
										,$cashpayamount
										,$result['data']['shelfinfo']['rebate_value']
										,$result['data']['shelfinfo']['rebate_model']
									);
			
			//发送可以发送的商品券
			$couponlist = service('Coupon')->select4UserTobeSendByOid($order_id,time());
			$sendcenter = service('SendCenter');
			$senData = $sendcenter->parseCouponSendData($couponlist);
			$sendcenter->send($senData);
		}
		return $result;
	}
	
	/** 支付成功后的处理 **/
	function payFail(){
		
	}
	
	
	/** 转到支付机构进行支付 **/
	function gotoPayment(){
		$this->gotoLogin();
		$itemType	=	$_POST['itemType'];	//$("#paytypeselect").find("#itemType").val()
		$itemId		=	$_POST['itemId'];	//itemId : $("#paytypeselect").find("#itemId").val()
		$selectedPayType	=	$_POST['selectedPayType'];	//payType : $("#paytypeselect").find("#payType").val()
		$this->assign('notJump', "true");//设置提示框跳转不跳转
		$result['status']=0;
		$result['msg']='未选择订单！';
		if(empty($selectedPayType))$this->error("请选择支付方式！");
		$paydict = service('Dict')->getAllDirectSubDicts('pay','code');
		if(!in_array($itemType,$paydict))$this->error("参数有误！");
		
		if(empty($itemId))$this->error($result['msg']);
		unset($result);
		if($itemType=='pay_order'){
			$result = $this->_gotoPayment4Order($itemId,$selectedPayType,"pay_order");
			if($result['status']==1){
				if($selectedPayType=='xxypay'){		//如果现金帐户支付，则到此已将支付记录录入数据库。直接跳转到成功提示界面
					$result = $this-> _doAfterPaySuccess($result);
					$this->success($result['msg']);	
				}else{
					echo $result['data'];
					exit;
				}
			}else{
				$this->error($result['msg']);	
			}
		}
		if($itemType=='pay_charge'){
			$camount	=	intval($_POST['camount']);	
			if($camount<1||$camount>1000){
				$this->error("充值金额需在1元~1000元之间！");
				exit;
			}
			$result = $this->_gotoPayment4Charge($itemId,$selectedPayType,"pay_charge",$camount);
			if($result['status']==1){
				echo $result['data'];
				exit;
			}else{
				$this->error($result['msg']);	
			}
		}
		$this->error("跳转支付界面失败！");
	}
	
	private function _gotoPayment4Order($oid,$selectedPayType,$itemType){
		$result = service('Order')->checkEffectiveBeforePay($oid);
		$orderinfo = $result['data'];
		if($result['status'] != 1){
			//$result['msg'] 		= '订单被管理员撤销！<br>撤销说明1：'.$orderinfo['remark'];
			return $result;
		}
		unset($result);
		$result['status']=1;
		if($selectedPayType=='xxypay'){			//现金帐户
			$result = service('PayProvider')->dealXxypayResult($oid,$itemType);
		}else{
			unset($result);
			$product = service('Product')->getByShelfId($orderinfo['shelf_id']);
			$pay_mode = $selectedPayType;
			$result = service('PayProvider')->gotoPayProvider(	$orderinfo['id']
																	,"商品：".$product['goods_title']
																	,"品牌：".$product['partner_title']."  数量：".$orderinfo['quantity']."件"
																	,$orderinfo['paid_money']-$orderinfo['had_pay_fee']	
																	,$pay_mode
																	,$itemType
																);
			$result['data'] = 	"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>".
								"<div style='display:none;'>".$result['data']."</div>".
								"</body></html>";
		}
		return $result;
	}
	
	private function _gotoPayment4Charge($cid,$selectedPayType,$itemType,$camount){
		exit;
		//$camount = "0.5";
		$pay_mode = $selectedPayType;
		global $ts;
		if(!in_array($pay_mode,array('xxypay','syspay'))){
			$result = service('PayProvider')->gotoPayProvider(	$cid
																,$_SESSION['uname']."账户充值"
																,$ts['site']['site_name']."账户充值，充值金额  ".$camount." 元"
																,$camount
																,$pay_mode
																,$itemType
															);
			$result['data'] =	"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>".
								"<div style='display:none;'>".$result['data']."</div></body></html>";
		}else{
			$result['status'] = -1;
			$result['msg'] = "请正确选择支付服务提供商！";
		}
		return $result;
	}
	
	public function alipay_return(){
		$this->assign('notJump', "true");//设置提示框跳转不跳转
		$result = service('PayProvider')->dealPayResult('alipay');
		$result = $this-> _doAfterPaySuccess($result);
		if($result['status']==1){
			$this->success('支付成功！<br>'.$result['msg']);
		}else{
			$this->error('支付失败！'.$result['msg']);
		}
		exit;
	}	
	
	//直接将结果，发给财富通。与支付宝处理方式不同。
	public function tenpay_return(){
		//$this->assign('notJump', "true");//设置提示框跳转不跳转
		$result = service('PayProvider')->dealPayResult('tenpay');
		$result = $this-> _doAfterPaySuccess($result);
		//echo $result['data'];
		echo $result['data'];
		exit;
	}	
	
	private function _doAfterPaySuccess($result){
		Log::write('PayAction._doAfterPaySuccess()->参数='.parseAry2Str($result),Log::DEBUG,Log::FILE);
			
		if($result['status']==1){
			$ary_payinfo = $result['PayInfo'];
			$itemType 	= $ary_payinfo['pay_type'];
			$itemId		= $ary_payinfo['item_id'];	
			$_SESSION['mid']=$ary_payinfo['uid'];
			if($itemType=='pay_order'){
				Log::write('PayAction._doAfterPaySuccess()->itemId='.$itemId.'  itemType='.$itemType."  执行订单成功后的操作！",Log::DEBUG,Log::FILE);
			
				$result_1 = $this->_payOrderSuccess($itemId);
			}
			if($itemType=='pay_charge'){
				Log::write('PayAction._doAfterPaySuccess()->itemId='.$itemId.'  itemType='.$itemType."  执行充值成功后的操作！",Log::DEBUG,Log::FILE);
			
				$uaccount = service('UserAccount')->refresh4UserCash();
				$result['status']=1;
				$result['msg']=$result['msg'].'充值成功！账户余额：'.formatMoney($uaccount['current_money']);;
			}
			
			//$result['msg'] = '支付成功！<br>请回到最初发起支付界面，点击弹出框的“已完成付款”按钮！<br>以便系统做进一步处理！'.$result['msg'];
			$result['msg'] = $result['msg'].$result_1['msg'];
		}else{
			$result['msg'] = $result['msg'];
		}
		return $result;
		
		/**
		 * $ary_payinfo=array(	'trade_no'=>$trade_no
							,'pay_type'=>$itemType
		 					,'item_id'=>$out_trade_no
							,'total_fee'=>$total_fee
		 					,'service'=>$pay_mode
		 					,'return_info'=>$serialize_return_info
		 					,'paytime'=>time()
		  					,'uid'=>$_uid
		 				);
		**/
	}
	
	//财付通支付成功显示页面
	public function tenpay_success(){
		$this->assign('notJump', "true");//设置提示框跳转不跳转
		$this->success('支付成功！');
		exit;
	}	
}
?>